#定义剧情树提取至json函数和剧情树提取至字典函数
#启动剧情树提取至json函数
init python:
    import os
    import json
    from parse_tracker import parse_script, save_storyline_to_json

    def generate_storyline_json():
        # 获取当前 game 文件夹路径
        game_dir = renpy.loader.transfn("script.rpy")
        script_file = os.path.join(os.path.dirname(game_dir), "script.rpy")
        output_file = os.path.join(os.path.dirname(game_dir), "storyline.json")

        try:
            storyline = parse_script(script_file)
            save_storyline_to_json(storyline, output_file)

            # 打印到开发者日志（Shift+O 打开 console 或 log.txt）
            renpy.log("剧情树 JSON 已生成: " + output_file)
            renpy.log(json.dumps(storyline, indent=4, ensure_ascii=False))

        except Exception as e:
            renpy.log("生成剧情树出错: " + str(e))
        
    def generate_storyline():
        """解析 script.rpy 并返回剧情字典"""
        script_file = renpy.loader.transfn("script.rpy")
        output_file = os.path.join(os.path.dirname(script_file), "storyline.json")

        storyline = parse_script(script_file)
        save_storyline_to_json(storyline, output_file)

        return storyline

    #启动剧情提取至json函数
    generate_storyline_json()
